package com.lagou.edu.loader;

import com.lagou.edu.annotation.Component;
import com.lagou.edu.annotation.Repository;
import com.lagou.edu.annotation.Scan;
import com.lagou.edu.annotation.Service;
import com.lagou.edu.factory.BeanFactory;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by swallow on 2020/10/25.
 */
public class Loader {
    List<String> paths = new ArrayList<>();

    public void load(Class config) {
        Scan scan = (Scan) config.getDeclaredAnnotation(Scan.class);
        String packageName = scan.value();
        List<Class> classList = scan(packageName);
        for (Class aClass : classList) {
            if (aClass.isAnnotationPresent(Component.class)) {
                Component component = (Component) aClass.getDeclaredAnnotation(Component.class);
                String id = component.value();
                BeanFactory.init(aClass, id);
            }
        }
        for (Class aClass : classList) {
            if (aClass.isAnnotationPresent(Repository.class)) {
                Repository repository = (Repository) aClass.getDeclaredAnnotation(Repository.class);
                String id = repository.value();
                BeanFactory.init(aClass, id);
            }
        }
        for (Class aClass : classList) {
            if (aClass.isAnnotationPresent(Service.class)) {
                Service service = (Service) aClass.getDeclaredAnnotation(Service.class);
                String id = service.value();
                BeanFactory.init(aClass, id);
            }
        }
    }

    private List<Class> scan(String packageName) {
        List<Class> list = new ArrayList<>();
        String classpath = this.getClass().getResource("/").getPath();
        packageName = packageName.replace(".", File.separator);
        String searchPath = classpath + packageName;
        List<String> pathList = doPath(new File(searchPath));
        for (String s : pathList) {
            s = s.replace(classpath.replace("/","\\").replaceFirst("\\\\",""),"").replace("\\",".").replace(".class","");
            Class cls = null;
            try {
                cls = Class.forName(s);
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
            if (cls != null) list.add(cls);
        }
        return list;
    }

    private List<String> doPath(File file) {
        if (file.isDirectory()) {//文件夹
            //文件夹我们就递归
            File[] files = file.listFiles();
            for (File f1 : files) {
                doPath(f1);
            }
        } else {//标准文件
            //标准文件我们就判断是否是class文件
            if (file.getName().endsWith(".class")) {
                //如果是class文件我们就放入我们的集合中。
                paths.add(file.getPath());
            }
        }
        return paths;
    }
}
